package com.wg.msuser.service;

import lombok.RequiredArgsConstructor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.URLEncoder;

@Service
@RequiredArgsConstructor
public class SimpleLocationService {
    private final OkHttpClient okHttpClient=new OkHttpClient();

    @Value("${amap.api.key}")
    private String apiKey;

    @Value("${amap.api.base-url}")
    private String baseUrl;

    /**
     * 最简单的IP定位
     * @param ip IP地址
     * @return 返回原始JSON字符串
     */
    public String ipLocation(String ip) throws IOException {
        String url = String.format("%s/ip?key=%s&ip=%s",
                baseUrl, apiKey, ip);

        Request request = new Request.Builder()
                .url(url)
                .build();

        try (Response response = okHttpClient.newCall(request).execute()) {
            return response.body().string();
        }
    }

    /**
     * 简单地址解析（地址转坐标）
     * @param address 如"北京市海淀区清华科技园"
     * @return 包含经纬度的JSON字符串
     */
    public String addressToLocation(String address) throws IOException {
        String url = String.format("%s/geocode/geo?key=%s&address=%s",
                baseUrl, apiKey, URLEncoder.encode(address, "UTF-8"));

        Request request = new Request.Builder()
                .url(url)
                .build();

        try (Response response = okHttpClient.newCall(request).execute()) {
            return response.body().string();
        }
    }

    /**
     * 简单逆地理编码（坐标转地址）
     * @param lng 经度
     * @param lat 纬度
     * @return 包含地址信息的JSON字符串
     */
    public String locationToAddress(double lng, double lat) throws IOException {
        String location = lng + "," + lat;
        String url = String.format("%s/geocode/regeo?key=%s&location=%s",
                baseUrl, apiKey, location);

        Request request = new Request.Builder()
                .url(url)
                .build();

        try (Response response = okHttpClient.newCall(request).execute()) {
            return response.body().string();
        }
    }
}